import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

# 设备配置
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 超参数
sequence_length = 28  # 序列长度
input_size = 28  # 输入大小
hidden_size = 128  # 隐含层大小
num_layers = 4  # GRU 层数
num_classes = 10  # 分类个数
batch_size = 100
num_epochs = 2
learning_rate = 0.01

# MNIST 数据集
train_dataset = torchvision.datasets.MNIST(root='./data/',
                                           train=True,
                                           transform=transforms.ToTensor(),
                                           download=True)

test_dataset = torchvision.datasets.MNIST(root='./data/',
                                          train=False,
                                          transform=transforms.ToTensor())

# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=batch_size,
                                          shuffle=False)


# Recurrent neural network (many-to-one) - 使用 GRU
class GRUModel(nn.Module):  # 类名改为 GRUModel
    def __init__(self, input_size, hidden_size, num_layers, num_classes):
        super(GRUModel, self).__init__()  # 类名改为 GRUModel
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        # 使用 nn.GRU 替代 nn.LSTM
        self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        # 设置初始的隐藏状态
        # GRU 只需要一个初始隐藏状态 h0，不需要 c0
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)

        # 前向传播 GRU
        # GRU 的输出 out 和 LSTM 一样，但只返回一个隐藏状态 _
        out, _ = self.gru(x, h0)

        # 解码最后一个时间步的隐藏状态
        out = self.fc(out[:, -1, :])
        return out


model = GRUModel(input_size, hidden_size, num_layers, num_classes).to(device)  # 使用 GRUModel

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.reshape(-1, sequence_length, input_size).to(device)
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i + 1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
                  .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))

# Test the model
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, sequence_length, input_size).to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))

# Save the model checkpoint
# torch.save(model.state_dict(), 'gru_model.ckpt') # 可以选择保存模型参数
